package com.rawchen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rawchen.config.RedisKeyConfig;
import com.rawchen.entity.Category;
import com.rawchen.exception.NotFoundException;
import com.rawchen.exception.PersistenceException;
import com.rawchen.mapper.CategoryMapper;
import com.rawchen.service.CategoryService;
import com.rawchen.service.RedisService;
import com.rawchen.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 博客分类业务层实现
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private TagService tagService;
	@Autowired
	private RedisService redisService;

	@Override
	public List<Category> getCategoryList() {
		return categoryMapper.selectList(null).stream().peek(category -> category.setBlogs(null)).toList();
	}

	@Override
	public List<Category> getCategoryNameList() {
		String redisKey = RedisKeyConfig.CATEGORY_NAME_LIST;
		List<Category> categoryListFromRedis = redisService.getListByValue(redisKey);
		if (categoryListFromRedis != null) {
			return categoryListFromRedis;
		}
		LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
		lqw.select(Category::getName);
		List<Category> categoryList = categoryMapper.selectList(lqw);
		redisService.saveListToValue(redisKey, categoryList);
		return categoryList;
	}

	@Transactional
	@Override
	public void saveCategory(Category category) {
		if (categoryMapper.insert(category) != 1) {
			throw new PersistenceException("分类添加失败");
		}
		redisService.deleteCacheByKey(RedisKeyConfig.CATEGORY_NAME_LIST);
	}

	@Override
	public Category getCategoryById(Long id) {
		Category category = categoryMapper.selectById(id);
		if (category == null) {
			throw new NotFoundException("分类不存在");
		}
		return category;
	}

	@Override
	public Category getCategoryByName(String name) {
		LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
		lqw.eq(Category::getName, name);
		return categoryMapper.selectOne(lqw); //name为unique的，不会抛异常
	}

	@Transactional
	@Override
	public void deleteCategoryById(Long id) {
		if (categoryMapper.deleteById(id) != 1) {
			throw new PersistenceException("删除分类失败");
		}
		redisService.deleteCacheByKey(RedisKeyConfig.CATEGORY_NAME_LIST);
	}

	@Transactional
	@Override
	public void updateCategory(Category category) {
		if (categoryMapper.updateById(category) != 1) {
			throw new PersistenceException("分类更新失败");
		}
		redisService.deleteCacheByKey(RedisKeyConfig.CATEGORY_NAME_LIST);
		//修改了分类名，可能有首页文章关联了分类，也要更新首页缓存
		redisService.deleteCacheByKey(RedisKeyConfig.HOME_BLOG_INFO_LIST);
	}
}
